<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

function plant_structure_list_page()
{
    @$output = drupal_render(drupal_get_form('plant_structure_list_form'));
    return $output;
}

function plant_structure_list_form($form, &$form_state)
{
    $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state);
    $form['address'] = _insert_address_selection_form($form, $form_state, 'address', 3, FALSE, '','','',TRUE);
    $form['plant_fuzzy_seach']['#markup'] = '<div class="plant-structure-fuzzy-search">';
    $form['plant']= _insert_plant_selection_form($form,$form_state,!empty($record) ? $record->plant_id:'');
    $form['plant_fuzzy_seach_close']['#markup'] = '</div>';
    $init_year =  !empty($form_state['values']['year'])?$form_state['values']['year']:"";
    _insert_date_selection_form($form,$form_state,5,$init_year,null,false);
    $fields = array(
        '' => '请选择',
        'quantity' => '种植面积',
    );
    numerical_range_search($form,$fields);
    $table['#markup'] =data_list_view_page($form, $form_state);
    ajax_submit_form($form, $form_state, $table, '');
    return $form;
}


function plant_structure_list_form_validate($form, &$form_state)
{

}

function data_list_view_page($form = '', &$form_state = '')
{
        global $user;
        $output = '';
        //表头
        $header = array(
            array('data' => '选择', 'class' => ['essential no']),
            array('data' => '年份', 'class' => ['integrant essential year'], 'field' => 'year'),
            array('data' => '省 市 县', 'class' => ['essential province city county']),
            array('data' => '作物', 'class' => ['essential plant']),
            array('data' => '种植面积', 'class' => ['integrant essential quantity'], 'field' => 'quantity'),
            array('data' => '操作', 'class' => ['essential more']),
        );
        $query = db_select('addr', 'A')->extend('PagerDefault')->extend('TableSort');//地址表
        $query->join('plant_structure', 'PS', 'A.addr_id=PS.addr_id');//内连接 成一个表
        $query->leftJoin('plant', 'P1', 'PS.plant_id=P1.plant_id');//需要得到植物名称
        $query->fields('PS');
        $query->addField('P1', 'plant_name');

        //地址级别查询
        _address_search_conditon($query,$form_state);
       
        if(!user_access('view all plant_structure') && user_access('view own plant_structure')){
            $query->condition('PS.author_uid',$user->uid, '=');
        }
        //模糊条件筛选

        if (!empty($form_state['values']['plant'])) {//模糊植物名字查询条件
            $query->condition('P1.plant_id', get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant']),'=',false);
        }
        if (!empty($form_state['values']['year'])) {//模糊年度查询条件
            $query->condition('PS.year', '%' . db_like($form_state['values']['year']) . '%', 'LIKE');
        }

        $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
        $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
        $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
        $query->addField('A1', 'name', 'province');
        $query->addField('A2', 'name', 'city');
        $query->addField('A3', 'name', 'county');

        if(!empty($form_state['values']['field'])){
            if(!empty($form_state['values']['min_number']) && !empty($form_state['values']['max_number'])){
                $db_and = db_and();
                $db_and->condition('PS.'.$form_state['values']['field'], $form_state['values']['min_number'], '>');
                $db_and->condition('PS.'.$form_state['values']['field'], $form_state['values']['max_number'], '<');
                $query->condition($db_and);
            }elseif(!empty($form_state['values']['min_number'])){
                $query->condition('PS.'.$form_state['values']['field'], $form_state['values']['min_number'], '>');
            }elseif(!empty($form_state['values']['max_number'])){
                $query->condition('PS.'.$form_state['values']['field'], $form_state['values']['max_number'], '<');
            }
        }
        if(empty($form_state['values']) || empty($form_state['values']['order'])) {
            $query->orderBy('PS.timestamp', 'DESC');
        }
        $query->limit(variable_get("list_page_item_number", 5));

        $plant_structureInfo = $query->orderByHeader($header)->execute();

        $rows = array();
        //表内容
        $n = 1;
        foreach ($plant_structureInfo as $row) {
            $city = $row->city ? ' '.$row->city :'';
            $county = $row->county ? ' '.$row->county :'';
            if (nonghua_user_access('plant_structure', 'delete', $row->plant_structure_id, $row->author_uid, 0)) {
                $disabled = ' class="listViewTableCheck" ';
            } else{
                $disabled = ' disabled="true" ';
            }
            $rows[] = array(
                array('data' => '<input type="checkbox"'.$disabled.' value ="' . $row->plant_structure_id . '"/>' . $n++, 'class' => ['integrant essential no']),
                array('data' => $row->year, 'class' => ['integrant goRight essential year']),
                array('data' => $row->province.$city.$county, 'class' => ['integrant essential province city county']),
                array('data' => $row->plant_name, 'class' => ['integrant haveTobr goRight essential plant']),
                array('data' => $row->quantity, 'class' => ['integrant essential quantity']),
                array('data' => '<a href="'.base_path().'plant_structure/edit/' . $row->plant_structure_id . '" data-toggle="modal" target = "_top"><img width="20px" height="20px" src="'.base_path().'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more'),
            );
        }


        $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('没有记录'), 'attributes' => array('class' => array('table table-bordered table-striped table-hover enhanced')))); //表格
        /*	 * *按钮** */
        if(sizeof($rows) > 0 && (user_access('delete own plant_structure') ||  user_access('delete all plant_structure'))) {
            $output .= '<a href="javascript:void(0)" id="listViewTableSelectAll" data-toggle="modal" class="btn btn-mini">全选</a>';
            $output .= '<a href="javascript:void(0)" id="listViewTableDeleteSelected" data-toggle="modal" class="btn btn-mini">删除所选</a>';
        }
        if(!empty($form_state['values']['village'])){
        $addr_id = $form_state['values']['village'];
            $str = 'village=';
        }elseif(!empty($form_state['values']['town'])){
            $addr_id = $form_state['values']['town'];
            $str = 'town=';
        }elseif(!empty($form_state['values']['county'])){
            $addr_id = $form_state['values']['county'];
            $str = 'county=';
        }elseif(!empty($form_state['values']['city'])){
            $addr_id = $form_state['values']['city'];
            $str = 'city=';
        }elseif(!empty($form_state['values']['province'])){
            $addr_id = $form_state['values']['province'];
            $str = 'province=';
        }
        $str .= $addr_id;
        $output .= '<a href="'.base_path().'plant_structure/export?'.$str.'&address_fuzzy='.$form_state['values']['address_fuzzy'].'&plant='.$form_state['values']['plant'].'&year='.$form_state['values']['year'].'&field='.$form_state['values']['field'].'&min_number='.$form_state['values']['min_number'].'&max_number='.$form_state['values']['max_number'].'" data-toggle="modal" class="btn btn-mini">导出</a>';
        $output .= theme('pager');
        return $output;
}

function plant_structure_delete()
{
    ajax_table_delete('plant_structure', 'plant_structure_id');
}


function plant_structure_export($form,&$form_state){
    $letter = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
    $tableheader = array('地址','植物','年份','种植面积');
    $data = get_plant_structure_data($form, $form_state);
    nonghua_php_excel($letter,$tableheader,$data,'种植结构数据');
}

function get_plant_structure_data($form = '', &$form_state = ''){
    global $user;
    $user_info = _get_user_info($user->uid);
   $query = db_select('addr', 'A');//地址表
    $query->join('plant_structure', 'PS', 'A.addr_id=PS.addr_id');//内连接 成一个表
    $query->leftJoin('plant', 'P1', 'PS.plant_id=P1.plant_id');//需要得到植物名称
    //地址级别查询
    if (!empty($_GET['town'])) {//乡镇级
        $query->condition('A.town_id', $_GET['town'], '=');
    } elseif (!empty($_GET['county'])) {//县级
        $query->condition('A.county_id', $_GET['county'], '=');
    } elseif (!empty($_GET['city'])) {//市级
        $query->condition('A.city_id', $_GET['city'], '=');
    } elseif (!empty($_GET['province'])) {//省级
        $query->condition('A.province_id', $_GET['province'], '=');
    }
    if (!empty($_GET['address_fuzzy'])) {
        if (!empty($_GET['city'])) {//县级
            $or = db_or()->condition('A3.name', '%' . db_like($_GET['address_fuzzy']) . '%', 'like')->condition('A2.name', '%' . db_like($_GET['address_fuzzy']) . '%', 'like');
        }elseif (!empty($_GET['province'])) {//省级
            $or = db_or()->condition('A3.name', '%' . db_like($_GET['address_fuzzy']) . '%', 'like')->condition('A2.name', '%' . db_like($_GET['address_fuzzy']) . '%', 'like')->condition('A1.name', '%' . db_like($_GET['address_fuzzy']) . '%', 'like');
        }else{
            $or = db_or()->condition('A3.name', '%' . db_like($_GET['address_fuzzy']) . '%', 'like')->condition('A2.name', '%' . db_like($_GET['address_fuzzy']) . '%', 'like')->condition('A1.name', '%' . db_like($_GET['address_fuzzy']) . '%', 'like')->condition('A.name', '%' . db_like($_GET['address_fuzzy']) . '%', 'like');
        }
        $query->condition($or);
    }
    if(!user_access('view all plant_structure') && user_access('view own plant_structure')){
        $query->condition('PS.author_uid',$user->uid, '=');
    }
    //模糊条件筛选
    if (!empty($_GET['fuzzy_address'])) {//模糊地址查询条件
        $query->condition('A.name', '%' . db_like($_GET['fuzzy_address']) . '%', 'LIKE');
    }
    if (!empty($_GET['plant'])) {//模糊植物名字查询条件
        $query->condition('P1.plant_name', '%' . db_like($_GET['plant']) . '%', 'LIKE');
    }
    if (!empty($_GET['year'])) {//模糊年度查询条件
        $query->condition('PS.year', '%' . db_like($_GET['year']) . '%', 'LIKE');
    }

    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    if(!empty($form_state['values']['field'])){
        if(!empty($_GET['min_number']) && !empty($_GET['max_number'])){
            $db_and = db_and();
            $db_and->condition('PS.'.$_GET['field'], $_GET['min_number'], '>');
            $db_and->condition('PS.'.$_GET['field'], $_GET['max_number'], '<');
            $query->condition($db_and);
        }elseif(!empty($_GET['min_number'])){
            $query->condition('PS.'.$_GET['field'], $_GET['min_number'], '>');
        }elseif(!empty($form_state['values']['max_number'])){
            $query->condition('PS.'.$_GET['field'], $_GET['max_number'], '<');
        }
    }
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');
    $query->addField('P1', 'plant_name');
    $query->fields('PS',array('year','quantity'));
    $plant_structureInfo = $query->execute()->fetchAll();

    foreach($plant_structureInfo as $k => $v){
        $plant_structureInfo[$k]->province= $v->province.$v->city.$v->county.$v->town.$v->village;
        unset($plant_structureInfo[$k]->city);
        unset($plant_structureInfo[$k]->county);
        unset($plant_structureInfo[$k]->town);
        unset($plant_structureInfo[$k]->village);
    }
    return $plant_structureInfo;
}